
package com.hq.web.shiro;

import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.hq.common.entity.Role;
import com.hq.common.entity.User;
import com.hq.common.user.IUserService;


public class MyShiroRealm extends AuthorizingRealm {

	private Logger logger = LoggerFactory.getLogger(MyShiroRealm.class);

	@Autowired
	private IUserService uesrApplication;

	/** 
     * 权限认证 
     */  
    @Override  
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {  
        //获取登录时输入的用户名  
        String loginName=(String) principalCollection.fromRealm(getName()).iterator().next();  
        //到数据库查是否有此对象  
        User user=uesrApplication.findByName(loginName);  
        if(user!=null){  
            //权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission）  
            SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();  
            //用户的角色集合  
            info.setRoles(uesrApplication.getRolesName(user)); 
            logger.info("用户角色："+uesrApplication.getRolesName(user));
            //用户的角色对应的所有权限，如果只使用角色定义访问权限，下面的四行可以不要  
            List<Role> roleList=uesrApplication.getRoleList(user);  
            for (Role role : roleList) {  
                info.addStringPermissions(uesrApplication.getPermissionsName(role.getId())); 
                logger.info("用户权限："+uesrApplication.getPermissionsName(role.getId()));
            }  
            return info;  
        }  
        return null;  
    }  
  
    /** 
     * 登录认证; 
     */  
    @Override  
    protected AuthenticationInfo doGetAuthenticationInfo(  
            AuthenticationToken authenticationToken) throws AuthenticationException {  
        //UsernamePasswordToken对象用来存放提交的登录信息  
        UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken; 
        Subject currentUser = SecurityUtils.getSubject();
        //查出是否有此用户  
        User user=uesrApplication.findByName(token.getUsername()); 
        if(user!=null){  
            //若存在，将此用户存放到登录认证info中  
        	currentUser.getSession().setAttribute(IUserService.SESSION_USERINFO, user);
            return new SimpleAuthenticationInfo(user.getName(), user.getPassword(), getName());  
        }  
        return null;  
    }
	/**
	 * 更新用户授权信息缓存.
	 */
	public void clearCachedAuthorizationInfo(String principal) {
		SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
		clearCachedAuthorizationInfo(principals);
	}

	/**
	 * 清除所有用户授权信息缓存.
	 */
	public void clearAllCachedAuthorizationInfo() {
		Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
		if (cache != null) {
			for (Object key : cache.keys()) {
				cache.remove(key);
			}
		}
	}

	
	

}
